<template>
  <view>
  </view>
</template>

<script setup>
import {useToast} from 'wot-design-uni';
const {error: showError} = useToast();

let main, receiver, filter;
let _codeQueryTag = false;
//广播列表
const broadcastConfigs = [
  {
    "id": 5,
    "model": "东集",
    "braodcastid": "com.seuic.scan",
    "broadcastvalue": "scannerdata"
  }
]
// 检查 plus 环境是否可用
const isPlusReady = () => {
  return typeof plus !== 'undefined' && typeof plus.android !== 'undefined';
};

const initScan = () => {
  if (!isPlusReady()) {
    showError({msg: '环境不可用，无法初始化扫描'});
    return;
  }
  try {
    main = plus.android.runtimeMainActivity(); // 获取 activity
    let IntentFilter = plus.android.importClass('android.content.IntentFilter');
    filter = new IntentFilter();

    broadcastConfigs.forEach(config => {
      filter.addAction(config.braodcastid);
    });
    // 广播动作
    receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
      onReceive: function (context, intent) {
        plus.android.importClass(intent);
        let action = intent.getAction();
        let config = broadcastConfigs.find(c => c.braodcastid === action);
        console.log('config',config)
        if (config) {
          let code = intent.getStringExtra(config.broadcastvalue);
          queryCode(code);
        }else{
          showError({msg: '未找到对应广播'});
        }
      }
    });
  } catch (error) {
    console.error('初始化扫描时出错:', error);
  }
};

// 启动扫描操作,将之前创建的广播接收器（receiver）注册到活动中,以便接收指定广播动作的结果
// filter 用于过滤广播消息，只有匹配过滤器中指定的广播动作的消息才会被接收和处理
const startScan = () => {
  if (!isPlusReady() || !main || !receiver || !filter) {
    showError({msg: '无法启动扫描，环境或资源不可用'});
    return;
  }
  try {
    main.registerReceiver(receiver, filter);
  } catch (error) {
    showError({msg: `启动扫描时出错${error}`});
  }
};

// 停止扫描操作,将之前注册的广播接收器（receiver）从活动中注销,以停止接收扫描结果的广播
const stopScan = () => {
  if (!isPlusReady() || !main || !receiver) {
    return;
  }
  try {
    main.unregisterReceiver(receiver);
  } catch (error) {
    console.error('停止扫描时出错:', error);
  }
};

const queryCode = (code) => {
  // 防重复
  if (_codeQueryTag) return false;
  _codeQueryTag = true;
  setTimeout(function () {
    _codeQueryTag = false;
  }, 150);
  // 触发自定义事件
  uni.$emit('scancode', {code: code});
};

onBeforeUnmount(()=>{
  stopScan();
})
onMounted(() => {
  initScan();
  startScan();
});
</script>
